import tkinter as tk
from tkinter import Tk, Frame, Label, Button, Text
import time
import socket
import threading

# tkinter version
print(f'tkinter version is {tk.TkVersion}')

# Initialize the main window
'''初始化主窗口'''
root = Tk()
root.title("The 7th Heaven")
root.geometry("800x600")
root.iconbitmap("email_64.ico")
root.resizable(False, False)
root.configure(bg="black")
# root.attributes("-alpha", 0.9)

# Global settings
'''全局设置'''
root.option_add("*Background", "black")
root.option_add("*Foreground", "green")
root.option_add("*Font", "Consolas 12")


def clear_frame():
    """Clear all widgets from the current frame."""
    for widget in root.winfo_children():
        widget.destroy()


def show_main():
    """Display the main page."""
    clear_frame()
    frame = Frame(root)
    frame.pack(expand=True, pady=50)

    Label(frame, text="Welcome to the 7th Heaven", font=("Consolas", 18, "bold")).grid(row=0, column=0, columnspan=2, pady=20)

    Button(frame, text="Chat Room", width=15, command=chat_room).grid(row=1, column=0, pady=10, padx=10)
    Button(frame, text="Login Room", width=15, command=show_login).grid(row=1, column=1, pady=10, padx=10)
    Button(frame, text="Exit", width=15, command=root.quit).grid(row=2, column=0, columnspan=2, pady=20)


def show_login():
    """Display the login page."""
    clear_frame()
    frame = Frame(root)
    frame.pack(pady=20)

    Label(frame, text="Seventh Heaven", font=("Consolas", 24, "bold")).grid(row=0, column=0, columnspan=2, pady=10)

    time_label = Label(frame, text="", font=("Consolas", 12))
    time_label.grid(row=1, column=0, columnspan=2)

    def update_time():
        current_time = time.strftime("%H:%M:%S")
        time_label.config(text=current_time)
        time_label.after(1000, update_time)

    update_time()

    Label(frame, text="Account:", anchor="e", width=10).grid(row=2, column=0, padx=10, pady=5)
    tk.Entry(frame, width=20).grid(row=2, column=1, pady=5)

    Label(frame, text="Password:", anchor="e", width=10).grid(row=3, column=0, padx=10, pady=5)
    tk.Entry(frame, width=20, show="●").grid(row=3, column=1, pady=5)

    Button(frame, text="Submit", command=lambda: print("Button clicked!")).grid(row=4, column=0, columnspan=2, pady=10)
    Button(frame, text="Back", command=show_main).grid(row=5, column=0, columnspan=2, pady=10)

def chat_room():
    """Display the chat room page."""
    clear_frame()
    frame = Frame(root)
    frame.pack(expand=True, pady=10)

    # 创建 socket 对象
    client_socket = None
    connected = False
    try:
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 连接服务器
        host = socket.gethostname()
        port = 9999
        client_socket.connect((host, port))
        connected = True
    except Exception as e:
        print(f"无法连接到服务器: {e}")
        connected = False

    Label(frame, text="Chat Room", font=("Consolas", 24, "bold")).grid(row=0, column=0, columnspan=3, pady=10)

    # 调整聊天显示区域大小
    chat_display = Text(frame, width=60, height=20, state="disabled", wrap="word", bg="black", fg="green")
    chat_display.grid(row=1, column=0, columnspan=3, pady=10, padx=10)

    input_box = tk.Entry(frame, width=43)
    input_box.grid(row=2, column=0, pady=10, padx=10, sticky="w")

    # 自动聚焦输入框
    input_box.focus_set()

    # 预定义颜文字列表
    emoji_list = ["(｡♥‿♥｡)", "(╯°□°）╯︵ ┻━┻", "(¬‿¬)", "(✿◠‿◠)", "(ಠ_ಠ)", "(ʘ‿ʘ)"]

    # 添加颜文字选择器
    def insert_emoji(emoji):
        """将选中的颜文字插入到输入框中"""
        input_box.insert("end", emoji)

    emoji_menu = tk.Menubutton(frame, text="😊", relief="raised")
    emoji_menu.grid(row=2, column=1, sticky="w")
    emoji_menu.menu = tk.Menu(emoji_menu, tearoff=0)
    emoji_menu["menu"] = emoji_menu.menu

    for emoji in emoji_list:
        emoji_menu.menu.add_command(label=emoji, command=lambda e=emoji: insert_emoji(e))

    if connected:
        # 接受服务端消息
        def receive_messages():
            """Receive messages from the server."""
            while True:
                try:
                    message = client_socket.recv(1024)
                    if not message:
                        break
                    chat_display.config(state="normal")
                    chat_display.insert("end", f"{message.decode('utf-8')}\n")  # 实时显示消息
                    chat_display.config(state="disabled")
                    chat_display.see("end")  # 滚动到底部
                except Exception as e:
                    print(f"Disconnected from the server: {e}")
                    break

        # 启动接收消息的线程
        threading.Thread(target=receive_messages, daemon=True).start()

        def send_message(event=None):
            """从输入框发送消息到服务器"""
            message = input_box.get()  # 从输入框中获取用户输入的消息
            if message.strip():  # 检查消息是否为空（去掉首尾空格后）
                chat_display.config(state="normal")  # 解锁聊天显示框，使其可编辑
                chat_display.insert("end", f"You: {message}\n")  # 在聊天框中插入用户的消息
                chat_display.config(state="disabled")  # 锁定聊天显示框，防止用户手动编辑
                chat_display.see("end")  # 滚动聊天框到底部，确保最新消息可见
                input_box.delete(0, "end")  # 清空输入框
                try:
                    client_socket.send(message.encode('utf-8'))  # 发送消息到服务器
                except Exception as e:
                    print(f"发送消息失败: {e}")

        input_box.bind("<Return>", send_message)
    else:
        # 离线模式下的消息发送
        chat_display.config(state="normal")
        chat_display.insert("end", "当前处于离线模式，无法连接到服务器。\n")  # 提示用户离线模式
        chat_display.config(state="disabled")

        def send_message(event=None):
            """在离线模式下发送消息"""
            message = input_box.get()  # 从输入框中获取用户输入的消息
            if message.strip():  # 检查消息是否为空（去掉首尾空格后）
                chat_display.config(state="normal")  # 解锁聊天显示框，使其可编辑
                chat_display.insert("end", f"You (offline): {message}\n")  # 在聊天框中插入用户的消息
                chat_display.config(state="disabled")  # 锁定聊天显示框，防止用户手动编辑
                chat_display.see("end")  # 滚动聊天框到底部，确保最新消息可见
                input_box.delete(0, "end")  # 清空输入框

        input_box.bind("<Return>", send_message)

    Button(frame, text="Send", command=send_message, width=10).grid(row=2, column=2, pady=10, padx=5, sticky="w")
    Button(frame, text="Clear", command=lambda: chat_display.config(state="normal") or chat_display.delete("1.0", "end") or chat_display.config(state="disabled"), width=10).grid(row=3, column=0, pady=10, padx=10, sticky="e")
    Button(frame, text="Back", command=show_main, width=10).grid(row=3, column=2, pady=10, padx=10, sticky="w")

# Show the main page
show_main()

# Start the main loop
root.mainloop()
